import React, { useState } from "react";
import { Form, Input, Button, message, Upload } from "antd";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { UserInfoApi, ChangeUserInfoApi } from "request/api";
import { connect } from "react-redux";
import { Dispatch } from "redux";

interface IProps {
  changeKeyFn: () => void;
}

function Means(props: IProps) {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState("");
  const getUserInfo = () => {
    UserInfoApi().then((res) => {
      console.log(res);
    });
  };

  const onFinish = (values: any) => {
    console.log("Success:", values);
    //调接口，修改用户名和密码
    ChangeUserInfoApi({
      username: values.username,
      password: values.password,
    }).then((res: any) => {
      if (res.errCode === 0) {
        message.success(res.message);
        //存储用户信息
        let { avatar, username } = res.data;
        localStorage.setItem("cms-avatar", avatar);
        localStorage.setItem("cms-username", username);
        localStorage.setItem("cms-token", res.data["cms-token"]);
        //更新Header组件
        props.changeKeyFn();
      }
      if (res.errCode === 1) {
        message.error(res.message);
      }
    });
  };

  const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  const UploadButton = () => (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const handleChange = (info: any) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      if (info.file.response.errCode === 0) {
        message.success("头像修改成功");
        //存储用户信息
        localStorage.setItem("cms-avatar", info.file.response.data.avatar);
        localStorage.setItem("cms-username", info.file.response.data.username);
        localStorage.setItem("cms-token", info.file.response.data["cms-token"]);
        //更新Header组件
        props.changeKeyFn();
      }

      setLoading(false);
    }
  };

  return (
    <div>
      <h1>修改资料</h1>

      <Form
        style={{ width: "500px" }}
        name='basic'
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete='off'
      >
        <Form.Item
          label='Username'
          name='username'
          rules={[{ required: true, message: "Please input your username!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label='Password'
          name='password'
          rules={[{ required: true, message: "Please input your password!" }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type='primary' htmlType='submit'>
            提交
          </Button>
        </Form.Item>
      </Form>

      <Upload
        name='avatar'
        listType='picture-card'
        className='avatar-uploader'
        showUploadList={false}
        action='http://localhost:9000/manage/upload'
        headers={{ "cms-token": localStorage.getItem("cms-token") as string }}
        beforeUpload={beforeUpload}
        onChange={handleChange}
      >
        {imageUrl ? (
          <img
            src={process.env.SERVER_HOST_PORT + imageUrl}
            alt='avatar'
            style={{ width: "100%" }}
          />
        ) : (
          <UploadButton />
        )}
      </Upload>
    </div>
  );
}
const mapDispatchProps = (dispatch: Dispatch) => {
  return {
    changeKeyFn() {
      dispatch({ type: "ChangeKey" });
    },
  };
};
export default connect(null, mapDispatchProps)(Means);
